package com.example.questionnaire.controller;

import com.example.questionnaire.model.User;
import com.example.questionnaire.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerUser(@RequestBody User user) {
        if (userRepository.findByUsername(user.getUsername()) != null) {
            return ResponseEntity.badRequest().body(createResponse("用户名已存在"));
        }
        if (userRepository.findByEmail(user.getEmail()) != null) {
            return ResponseEntity.badRequest().body(createResponse("邮箱已存在"));
        }

        User savedUser = userRepository.save(user);
        Map<String, Object> response = createResponse("注册成功");
        response.put("user", savedUser);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> loginUser(@RequestBody LoginRequest loginRequest) {
        User user = userRepository.findByUsername(loginRequest.getUsername());

        if (user == null || !user.getPassword().equals(loginRequest.getPassword()) || !user.getUserType().equals(loginRequest.getUserType())) {
            return ResponseEntity.badRequest().body(createResponse("登录失败：用户名、密码或用户类型错误"));
        }

        Map<String, Object> response = createResponse("登录成功");
        response.put("user", user);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/all")
    public ResponseEntity<List<User>> getAllUsers() {
        List<User> users = userRepository.findAll();
        return ResponseEntity.ok(users);
    }

    @PutMapping("/{id}/type")
    public ResponseEntity<Map<String, Object>> updateUserType(@PathVariable Long id, @RequestBody UserTypeDTO dto) {
        User user = userRepository.findById(id).orElse(null);
        if (user == null) {
            return ResponseEntity.badRequest().body(createResponse("用户不存在"));
        }

        user.setUserType(dto.getUserType());
        userRepository.save(user);
        return ResponseEntity.ok(createResponse("用户类型更新成功"));
    }

    @PutMapping("/{id}/toggle")
    public ResponseEntity<Map<String, Object>> toggleUserStatus(@PathVariable Long id, @RequestBody UserStatusDTO dto) {
        User user = userRepository.findById(id).orElse(null);
        if (user == null) {
            return ResponseEntity.badRequest().body(createResponse("用户不存在"));
        }

        user.setActive(dto.isActive());
        userRepository.save(user);
        return ResponseEntity.ok(createResponse("用户状态更新成功"));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(@PathVariable Long id) {
        logger.info("Attempting to delete user with ID: {}", id);

        User user = userRepository.findById(id).orElse(null);
        if (user == null) {
            logger.warn("User not found with ID: {}", id);
            return ResponseEntity.badRequest().body(createResponse("用户不存在"));
        }

        userRepository.delete(user);
        logger.info("User deleted successfully with ID: {}", id);
        return ResponseEntity.ok(createResponse("用户删除成功"));
    }

    // 辅助方法，创建响应体
    private Map<String, Object> createResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("message", message);
        return response;
    }
}